package com.zg.system.cms;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.common.core.R;
import com.zg.common.core.dao.cms.CmsBanner;
import com.zg.common.core.dao.cms.CmsBannerDao;
import com.zg.common.core.dao.cms.CmsBannerItem;
import com.zg.common.core.dao.cms.CmsBannerItemDao;
import com.zg.system.cms.service.BannerService;
import com.zg.system.cms.vo.*;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author
 */
@RestController
@RequiredArgsConstructor
public class BannerController {

    private final CmsBannerDao bannerDao;
    private final CmsBannerItemDao bannerItemDao;
    private final BannerService bannerService;

    @GetMapping("/banner/page")
    @ApiOperation("列表分页")
    public R page(Boolean isUse, String searchStr, Integer page, Integer pageSize) {
        LambdaQueryWrapper<CmsBanner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (isUse != null) {
            lambdaQueryWrapper.eq(CmsBanner::getIsUse, isUse);
        }
        if (StrUtil.isNotBlank(searchStr)) {
            lambdaQueryWrapper.like(CmsBanner::getSearchStr, "%" + searchStr + "%");
        }
        lambdaQueryWrapper.orderByDesc(CmsBanner::getCreateTime);
        IPage<CmsBanner> pb = bannerDao.page(
                new Page<>(page, pageSize),
                lambdaQueryWrapper);
        return R.success(pb);
    }

    @PostMapping("/banner/add")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("新增")
    public R add(@RequestBody AddBannerVo param) {
        long count = bannerDao.count(
                new LambdaQueryWrapper<CmsBanner>()
                        .eq(CmsBanner::getName, param.getName())
        );
        if (count > 0) {
            return R.error("名称重复！");
        }
        CmsBanner obj = new CmsBanner();
        obj.setName(param.getName());
        obj.setSearchStr(param.getName());
        obj.setSpeed(param.getSpeed());
        obj.setIsUse(param.getIsUse());
        bannerDao.save(obj);
        if(param.getIsUse()){
            //只能有一个是启用状态
            bannerDao.update(
                    new LambdaUpdateWrapper<CmsBanner>()
                            .eq(CmsBanner::getIsUse, true)
                            .ne(CmsBanner::getId, obj.getId())
                            .set(CmsBanner::getIsUse, false)
            );
        }
        return R.success();
    }

    @PostMapping("/banner/update")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("更新")
    public R update(@RequestBody UpdateBannerVo param) {
        CmsBanner old = bannerDao.getById(param.getId());
        long count = bannerDao.count(
                new LambdaQueryWrapper<CmsBanner>()
                        .eq(CmsBanner::getName, param.getName())
                        .ne(CmsBanner::getId, old.getId())
        );
        if (count > 0) {
            return R.error("名称重复！");
        }

        old.setName(param.getName());
        old.setSearchStr(param.getName());
        old.setSpeed(param.getSpeed());
        old.setIsUse(param.getIsUse());
        bannerDao.updateById(old);
        if(param.getIsUse()){
            //只能有一个是启用状态
            bannerDao.update(
                    new LambdaUpdateWrapper<CmsBanner>()
                            .eq(CmsBanner::getIsUse, true)
                            .ne(CmsBanner::getId, old.getId())
                            .set(CmsBanner::getIsUse, false)
            );
        }
        return R.success();
    }

    @GetMapping("/banner/list")
    @ApiOperation("列表")
    public R list() {
        List<CmsBanner> list = bannerDao.list(
                new LambdaQueryWrapper<CmsBanner>()
                        .orderByDesc(CmsBanner::getCreateTime));
        return R.success(list);
    }

    @PostMapping("/banner/batch")
    public R batch(@RequestBody BatchBannerVo param) {
        List<CmsBanner> list = bannerDao.list(
                new LambdaQueryWrapper<CmsBanner>()
                        .in(CmsBanner::getId, param.getIdList()));
        list.stream().forEach(t -> {
            if (param.getSpeedCk()) {
                t.setSpeed(param.getSpeed());
            }
            if (param.getIsUseCk()) {
                t.setIsUse(param.getIsUse());
            }
            bannerDao.updateById(t);
        });
        return R.success();
    }

    @PostMapping("/banner/del")
    public R del(@RequestBody List<Long> ids) {
        bannerDao.removeBatchByIds(ids);
        return R.success();
    }

    @GetMapping("/banner/img/list")
    public R findImgList(Long bannerId) {
        List<CmsBannerItem> list = bannerItemDao.list(
                new LambdaQueryWrapper<CmsBannerItem>()
                        .eq(CmsBannerItem::getBannerId, bannerId)
                        .orderByAsc(CmsBannerItem::getSort)
        );
        return R.success(list);
    }

    @PostMapping("/banner/img/add")
    public R addImg(@RequestBody AddBannerItemVo param) {
        CmsBannerItem obj = new CmsBannerItem();
        obj.setBannerId(param.getBannerId());
        obj.setImgUrl(param.getImgUrl());
        obj.setTitle(param.getTitle());
        obj.setLinkType(1);
        obj.setLinkUrl("");
        obj.setSort(param.getSort());
        bannerItemDao.save(obj);
        return R.success();
    }

    @PostMapping("/banner/img/del")
    public R delImg(@RequestBody List<Long> ids) {
        bannerItemDao.removeBatchByIds(ids);
        return R.success();
    }

    @PostMapping("/banner/img/save")
    public R saveImg(@RequestBody UpdateBannerItemVo param) {
        CmsBannerItem old = bannerItemDao.getById(param.getId());
        old.setTitle(param.getTitle());
        old.setLinkType(param.getLinkType());
        old.setLinkUrl(param.getLinkUrl());
        old.setContent(param.getContent());
        bannerItemDao.updateById(old);
        return R.success();
    }

    @PostMapping("/banner/img/sort")
    public R saveImgSort(String sortStr) {
        if (StrUtil.isBlank((sortStr))) {
            return R.error("请输入排序参数！");
        }
        bannerService.sortItem(sortStr);
        return R.success();
    }

    @PostMapping("/banner/update/isUse")
    public R updateUse(@RequestBody UpdateBannerVo param) {
        if (param.getIsUse()) {
            List<CmsBanner> list = bannerDao.list(
                    new LambdaQueryWrapper<CmsBanner>()
                            .eq(CmsBanner::getIsUse, true));
            list.forEach(t -> {
                t.setIsUse(false);
                bannerDao.updateById(t);
            });
        }
        CmsBanner obj = bannerDao.getById(param.getId());
        obj.setIsUse(param.getIsUse());
        bannerDao.updateById(obj);
        return R.success();
    }
}
